<?php
namespace app\task\controller;

class Task extends Base
{
    private $tn = 'task';

       
    //系统任务
    public function system(){

        if (isset($this->get['page']) && isset($this->get['limit'])) {
            $where = [];
            if(isset($this->get['keywords'])){
                $where['title'] = ['like','%'.$this->get['keywords'].'%'];
            }
            if(isset($this->get['date'])){
                $where['add_time'] = ['between',[strtotime($this->get['date']),strtotime($this->get['date']."+1 day")]];
            }
            if(isset($this->get['status'])){
                $where['status'] = $this->get['status'];
            }
            if(isset($this->get['type'])){
                $where['type'] = $this->get['type'];
            }

            $list  = db($this->tn)->order(['id' => 'desc'])->page($this->get['page'])->limit($this->get['limit'])->where($where)->field(true)->select();
            $order = db('order');
            foreach($list as $key=>$val){
                //如果任务没有完成并且有效时间超过当前时间则同样视为失效
                if($val['status'] == 2 && $val['validate_time'] < time() || $val['status'] == 3 && $val['validate_time'] < time()){
                    $list[$key]['status'] = 5;
                }

                if($val['status'] == 3 && $val['validate_time'] > time()){
                    //查看订单是否存在待提交审核
                    if(db('order')->where('task_id',$val['id'])->where('status',2)->find()){
                     
                        $list[$key]['status'] = 7;
                        
                    }
                }
                $list[$key]['up_time'] = date('m-d H:i',$val['add_time']);
                $list[$key]['validate_time'] = date('m-d H:i',$val['validate_time']);
                
            }
            $count = db($this->tn)->where($where)->count();
            $this->returnAPI('', 0, $list, ['count' => $count]);
        }
        return $this->fetch();
    }
   
    //添加系统任务
    public function add($id = 0){
        $model = model($this->tn);
        if($this->post){
            $id = $this->post['id'];
            $img_arr = '';
          
            unset($this->post['id']);
            if($id){
                $model = $model->get($id);
                if(!$model){
                    $this->returnAPI('信息有误，请稍后重试');
                }
                $img_arr = $model['image'];
               
            }
            $this->post['type'] = 1;
            $this->post['validate_time'] = strtotime('+'.intval($this->post['hours']).' hours');
            //价格
            $this->post['status'] = 2;
            if(isset($this->post['image'])){
                $img = [];
              
                foreach($this->post['image'] as $key=>$val){
                    $res = base_upload($val,'task/');
                    if($res['status'] == 0){
                        $this->returnAPI($res['msg']);
                    }
                    $img[] = $ori_img = $res['data'];
                   
                }
                if($img_arr){
                    $img_arr .= ','.implode(',',$img);

                }else{
                     $img_arr = implode(',',$img);
                }
                
                $this->post['image'] = $img_arr;
            }
            $res = $model->allowField(true)->save($this->post);
            if($res){
                $this->returnAPI('操作成功', 0);
            }
             $this->returnAPI($model->getError());
        }
        $data = $model->get($id);
        if(!is_null($data)){
            $data['image'] = $data['image']?explode(',',$data['image']):[];
            if($data['add_time'] < time()-24*3600){
                $data['status'] = 5;
            }
        }
          $order = db('order')->alias('o')->join('user u','u.id = o.user_id')->where(['o.task_id'=>$id,'status'=>['neq',5]])->order('add_time desc')->field('photo_path,nick_name,account,o.status,o.add_time')->select();
        return $this->fetch('', [
            'data' => $data,
            'order'=>$order
        ]);
    }

    //查看详情
    public function detail($id){
        $model = model($this->tn);
        if($this->post){
            $id = $this->post['id'];
            unset($this->post['id']);
            if($id){
                $model = $model->get($id);
                if(!$model){
                    $this->returnAPI('信息有误，请稍后重试');
                }
            }
            $res = $model->allowField(true)->save(['sort'=>$this->post['sort']]);
            if($res){
                $this->returnAPI('操作成功', 0);
            }
             $this->returnAPI($model->getError());
        }
        $data = $model->alias('t')->join('user u','u.id = t.user_id')->where('t.id',$id)->field('t.*,nick_name,photo_path,sign,sex')->find();
        if($data['image']){
                    $data['image'] = explode(',',$data['image']);
                }else{
                    $data['image'] = [];
                }

        $order = db('order')->alias('o')->join('user u','u.id = o.user_id')->where(['o.task_id'=>$id,'status'=>['neq',5]])->order('add_time desc')->field('photo_path,nick_name,account,o.status,o.add_time')->select();
        return $this->fetch('edit',['data'=>$data,'order'=>$order]);
    }

    //审核通过
    public function checkSuccess($id){
        $model = model($this->tn)->get($id);
        if(is_null($model)){
            $this->returnAPI('信息有误，请稍后重试');
        }
        db()->startTrans();
        if(!$model->save(['status'=>2,'validate_time'=>strtotime('+'.$model['hours'].' hours')])){
            db()->rollback();
            $this->returnAPI('审核失败，请稍后再试');
        }
        
        //扣除广告条数
        if(!db('user')->where('id',$model['user_id'])->setDec('f_credit')){
            db()->rollback();
            $this->apiReturn(0,'扣除广告条数失败');
        }
        //添加操作记录
        if(!db('handle_log')->insert(['user_id'=>$model['user_id'],'content'=>'扣除广告条数','handle_num'=>'-1','handle_type'=>2,'classify'=>2,'foreign_key'=>$id,'add_time'=>time()])){
            db()->rollback();
            $this->returnAPI('添加操作失败');
        }
        //添加消息
        if(!db('information')->insert(['user_id'=>$model['user_id'],'type'=>1,'title'=>'扣除广告条数','content'=>'-1','add_time'=>time()])){
             db()->rollback();
            $this->returnAPI('添加信息失败');
        }

        db()->commit();
        $this->returnAPI('审核成功',0);
    }

    //审核驳回
    public function checkError($id){
        $model = model($this->tn)->get($id);
        if(is_null($model)){
            $this->returnAPI('信息有误，请稍后重试');
        }
        db()->startTrans();
        if(!$model->save(['status'=>6])){
            db()->rollback();
            $this->returnAPI('审核失败，请稍后再试');
        }
        if(!db('user')->where('id',$model['user_id'])->setDec('f_credit')){
            db()->rollback();
            $this->returnAPI('冻结广告条数操作失败');
        }
        if(!db('user')->where('id',$model['user_id'])->setInc('credit')){
            db()->rollback();
            $this->returnAPI('广告条数操作失败');
        }
        db()->commit();
        $this->returnAPI('审核成功',0);
    }
    //删除任务
    public function delTask($id){
        $model = model($this->tn)->get($id);
        if(is_null($model)){
            $this->returnAPI('信息有误，请稍后重试');
        }
        if(!in_array($model['status'],[2,5])){
            $this->returnAPI('该任务已被接单');
        }
        if($model['image']){
            $img = explode(',',$model['image']);
            foreach($img as $key=>$val){
                if(file_exists('.'.$val)){
                    unlink('.'.$val);
                }
            }
        }
        if(!$model->delete()){
            $this->returnAPI('删除失败，请稍后再试');
        }
        $this->returnAPI('删除成功',0);
    }

    public function delImg($path,$id){
        $model = model($this->tn)->get($id);
        if(is_null($model) && !$model['thumb_image']){
            $this->returnAPI('信息有误，请稍后重试');
        }
        $image = explode(',',$model['thumb_image']);
        $image1 = explode(',',$model['image']);
        $index = array_search($path,$image);
        if($index === false){
            $this->returnAPI('该图片不存在');
        }
        array_splice($image1,$index,1);
        array_splice($image,$index,1);
        if(!db('task')->where('id',$id)->update(['thumb_image'=>implode(',',$image),'image'=>implode(',',$image1)])){
            $this->returnAPI('删除失败，请稍后再试');
        }
        $ori_img = str_replace('thumb/thumb_150_150_','',$path);
   
        if(file_exists('.'.$ori_img)){
            unlink('.'.$ori_img);
        }
        if(file_exists('.'.$path)){
            unlink('.'.$path);
        }

         $this->returnAPI('删除成功', 1);
    }   
}
